import originJSONP from 'jsonp'

/**
 * 对jsonp进行封装
 * @param {String} url
 * @param {Object} data
 * @param {Object} option
 */
export default function (url, data, option) {
  url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)
  return new Promise((resolve, reject) => {
    originJSONP(url, option, (err, data) => {
      if (!err) {
        resolve(data)
      } else {
        reject(err)
      }
    })
  })
}

/**
 * url的query
 * @param {String} data
 */
function param (data) {
  let url = ''
  for (const key in data) {
    let value = data[key] === undefined ? '' : data[key]
    url += `&${key} = ${encodeURIComponent(value)}`
  }
  return url ? url.substring(1) : ''
}
